package middleware

import (
	"go-oj-backend/v1/helper"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 管理员权限校验
func AuthAdminCheck() gin.HandlerFunc {
	mid := func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		userClaim, err := helper.AnalyseToken(token)
		if err != nil {
			c.Abort()
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": http.StatusUnauthorized,
				"msg":  "Unauthorized Authorization",
			})
			return
		}
		if userClaim == nil || userClaim.IsAdmin != 1 {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"code": http.StatusUnauthorized,
				"msg":  "Unauthorized Admin",
			})
			return
		}
		c.Next()
	}
	return mid
}

// 用户权限校验
func AuthUserCheck() gin.HandlerFunc {
	mid := func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		userClaim, err := helper.AnalyseToken(token)
		if err != nil {
			c.Abort()
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": http.StatusUnauthorized,
				"msg":  "Unauthorized Authorization",
			})
			return
		}
		if userClaim == nil {
			c.Abort()
			c.JSON(http.StatusOK, gin.H{
				"code": http.StatusUnauthorized,
				"msg":  "Unauthorized User",
			})
			return
		}
		// todo: migrate "user_claims" as define field
		c.Set("user_claims", userClaim)
		c.Next()
	}
	return mid
}
